package com.chennan.spring.demo.annotation.conditional;

import com.chennan.spring.modal.Person;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.annotation.*;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.MethodMetadata;

/**
 * @author chennan
 * @create 2021-11
 */
@Configuration
public class MyCditionalConfig {

    @Conditional(tom.class)
    @Bean
    public Person tom(){
        return new Person("tom",1);
    }
    @Conditional(tom.class)
    @Bean
    public Person mic(){
        return new Person("mic",2);
    }

    @Conditional(tom.class)
    @Bean
    public Person jemes(){
        return new Person("jemes",3);
    }
}
class tom implements Condition{

    /**
     * Determine if the condition matches.
     *
     * @param context  the condition context
     * @param metadata metadata of the {@link AnnotationMetadata class}
     *                 or {@link MethodMetadata method} being checked
     * @return {@code true} if the condition matches and the component can be registered,
     * or {@code false} to veto the annotated component's registration
     */
    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
        Environment environment = context.getEnvironment();
        String property = environment.getProperty("os.name");
        if(property.equals("tom")){
            return true;
        }
        return false;
    }
}